import { getMenuList, getFormList } from '@/api/application'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  menu:[]
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_MENU:(state,payload)=>{
    state.menu = payload
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  getMenuList({ commit , rootState, rootGetters}){
    return new Promise((resolve,reject)=>{

      const appId = rootState.application.appId  // appId 要跳转的应用id， innerApps内置应用
      const isInnerApp = rootGetters['application/isInnerApp']   // isInnerApp 要跳转的应用是否为内置应用

      if(isInnerApp) {
        getMenuList({appId}).then(res=>{
          if(res.code === 200){
            // const data = 
            // [
            //   {
            //     id:'www',
            //     icon:'el-icon-document',
            //     name:'轻应用管理',
            //     url:'manage'
            //   },
            //   {
            //     id:'ddd',
            //     icon:'el-icon-document',
            //     name:'角色管理',
            //     url:'sys-role'
            //   }
            // ]

            commit('SET_MENU',res.data)
            resolve()
          }else{
            this.$message.error('获取用户菜单信息列表失败')
            reject()
          }
        }).catch(()=>{reject()})
      }else {
        
        getFormList({appId}).then(res=>{
          const menuItems = []
         
          if(res.code == 200 && Array.isArray(res.data)) {
            res.data.forEach((item, index) => {
              menuItems.push({
                id: index,
                url:'common/' + item.busiKey,
                name: item.title , 
                icon:'el-icon-document',
                hasChildren:false
              })
            })
            commit('SET_MENU',menuItems)
            resolve()
          }else {
            reject()
            this.$message.error('获取用户菜单信息列表失败')
          }
        }).catch(()=>{reject()})
      }

    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
